package com.ljp.chat.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ljp.chat.entity.pojo.Account;
import com.ljp.chat.entity.pojo.User;
import com.ljp.chat.entity.request.UserInfo;
import com.ljp.chat.mapper.UserMapper;
import com.ljp.chat.service.AccountService;
import com.ljp.chat.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljp.chat.support.expansion.service.UniqueCheck;
import com.ljp.chat.utils.AccountUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author LvJunPeng
 * @since 2022-11-02
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final AccountService accountService;

    public UserServiceImpl(AccountService accountService) {
        this.accountService = accountService;
    }

    @Override
    public String saveUser(UserInfo userInfo) throws Exception {
        User user = new User();
        Account account = new Account();
        BeanUtil.copyProperties(userInfo, user);
        BeanUtil.copyProperties(userInfo, account);

        //设置账号
        account.setAccount(AccountUtils.getAccount()).setStatus(true).setAuthority(true);
        //设置账号星座信息
        user.setConstellation(AccountUtils.getConstellation(userInfo.getBirthday())).setAccount(account.getAccount());

        //唯一性校验
        UniqueCheck.uniqueCheck(user, UniqueCheck.INSERT, "is_delete");
        UniqueCheck.uniqueCheck(account, UniqueCheck.INSERT, "is_delete");

        accountService.save(account);
        this.save(user);
        return account.getAccount();
    }

    @Override
    public boolean updateUser(User user) throws Exception {
        //唯一性校验
        UniqueCheck.uniqueCheck(user, UniqueCheck.UPDATE, "is_delete");
        return this.updateById(user);
    }

}
